<script setup lang="ts">
import AMapLoader from "@amap/amap-jsapi-loader";
import { ref, onMounted, computed, nextTick } from "vue";
import cameraPng from "@/assets/img/camera.png";
import daosanjiao from "@/assets/img/daosanjiao.png";
import geoJsonData from "./qjwzzj";

window._AMapSecurityConfig = {
  securityJsCode: "9cd1aded40ea981870fadaf05b9bcb1c",
};
withDefaults(
  defineProps<{
    // 结束数值
    title: number | string;
  }>(),
  {
    title: "地图",
  }
);
let map = null;

const locations = [
  { name: "瞿家湾游客接待中心", position: [113.19991, 29.962895] },
  { name: "基地营地", position: [113.193226, 29.963163] },
];

function getCenter(PolygonArr) {
  // console.log('PolygonArr', PolygonArr)数据格式:[[lng,lat],[lng,lat]......]
  let total = PolygonArr.length;
  let X = 0;
  let Y = 0;
  let Z = 0;
  PolygonArr.forEach((lnglat) => {
    let lng = (lnglat[0] * Math.PI) / 180;
    let lat = (lnglat[1] * Math.PI) / 180;
    let x, y, z;
    x = Math.cos(lat) * Math.cos(lng);
    y = Math.cos(lat) * Math.sin(lng);
    z = Math.sin(lat);
    X += x;
    Y += y;
    Z += z;
  });
  X = X / total;
  Y = Y / total;
  Z = Z / total;

  let Lng = Math.atan2(Y, X);
  let Hyp = Math.sqrt(X * X + Y * Y);
  let Lat = Math.atan2(Z, Hyp);
  return [(Lng * 180) / Math.PI, (Lat * 180) / Math.PI];
}

const customContent = `
  <div style="border-radius: 5px; font-size: 16px; display: flex; flex-direction: column; align-items: center; width: 40px;">
    <div style="border: 2px solid #70A195; display: flex; align-items: center; justify-content: center; width: 40px; height: 40px;">
      <img src="${cameraPng}" style="width: 20px; height: 20px;">
    </div>
    <img src="${daosanjiao}" style="width: 30px; height: 15px">
  </div>
`;

const markerArr = []

const initMap = () => {
  var opts = {
    subdistrict: 0, //返回下一级行政区
    extensions: "all", //返回行政区边界坐标组等具体信息
  };
  AMapLoader.load({
    key: "37bc1997ec271cd7edcaffab7e923f4e",
    version: "2.0",
    plugins: [
      "AMap.DistrictSearch",
      "AMap.DistrictLayer",
      "AMap.TileLayer",
      "AMap.GeoJSON",
    ],
  }).then((AMap) => {
    //实例化DistrictSearch
    var district = new AMap.DistrictSearch(opts);
    district.search("荆州市", function (status, result) {
      var bounds = result.districtList[0].boundaries;
      var mask = [];
      for (var i = 0; i < bounds.length; i += 1) {
        mask.push([bounds[i]]);
      }
      var disCountry = new AMap.DistrictLayer.World({
        zIndex: 1,
        rejectMapMask: true,
      });
      var map = new AMap.Map("mapContainer", {
        mask: mask,
        center: [113.19991, 29.962895],
        viewMode: "3D",
        labelzIndex: 130,
        zoom: 15,
        cursor: "pointer",
        layers: [
          new AMap.TileLayer.RoadNet({
            zIndex: 7,
          }),
          disCountry,
          new AMap.TileLayer.Satellite(),
        ],
      });
      locations.forEach((location) => {
        // 创建标记物
        const marker = new AMap.Marker({
          position: location.position,
          map: map,
          // content: customContent,
          // label: {
          //   content: location.name,
          //   offset: new AMap.Pixel(Number(`-${location.name.length * 8}`), -30),
          //   color: "#fff",
          // },
        });
        markerArr.push(marker)
      });
      const coordinates = geoJsonData.features[0].geometry.coordinates;
      const center = getCenter(coordinates[0])

      const text = new AMap.Text({
        position: center,
        text: "瞿家湾镇", // 文字内容
        anchor: "center", // 设置文字位置
        style: {
          color: "#ddd", // 文字颜色
          fontSize: "30px",
          backgroundColor: "transparent", // 无背景
          border: "none",
        },
      });

      // 使用 AMap.GeoJSON 添加到地图
      const geojson = new AMap.GeoJSON({
        geoJSON: geoJsonData,
        getPolygon: (geojsonFeature, lnglats) => {
          return new AMap.Polygon({
            path: lnglats,
            strokeColor: "#25CCF7", // 线颜色
            strokeWeight: 2, // 线宽
            fillColor: "none", // 填充颜色
            // fillOpacity: 0.5, // 填充透明度
          });
        },
      });

      // 添加到地图
      map.add(geojson);
      map.add(text);
      // 调整视野
      // map.setFitView();

      map.on('zoomend', () => {
        var zoom = map.getZoom()
        console.log('zoom', zoom);
        if (zoom > 14) {
          markerArr.forEach((marker, index) => {
            marker.setLabel({
              content: locations[index].name,
              offset: new AMap.Pixel(Number(`-${locations[index].name.length * 8}`), -30),
            })
          })
        } else {
          markerArr.forEach((marker, index) => {
            marker.setLabel({
              content: null
            })
          })
        }
      });
    });
  });
};

onMounted(() => {
  initMap();
});
</script>

<template>
  <div class="centermap">
    <div class="maptitle">
      <div class="zuo"></div>
      <span class="titletext">{{ title }}</span>
      <div class="you"></div>
    </div>
    <div class="mapwrap">
      <BorderBox13>
        <div class="quanguo">瞿家湾</div>
        <div id="mapContainer"></div>
      </BorderBox13>
    </div>
  </div>
</template>

<style>
.amap-marker-label {
  background-color: transparent !important;
  border: none !important;
  color: white !important;
}

.amap-logo, .amap-copyright {
  display: none !important;
}
</style>

<style scoped lang="scss">
#mapContainer {
  height: 100%;
}

.centermap {
  margin-bottom: 30px;

  .maptitle {
    height: 60px;
    display: flex;
    justify-content: center;
    padding-top: 10px;
    box-sizing: border-box;

    .titletext {
      font-size: 28px;
      font-weight: 900;
      letter-spacing: 6px;
      background: linear-gradient(
        92deg,
        #0072ff 0%,
        #00eaff 48.8525390625%,
        #01aaff 100%
      );
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin: 0 10px;
    }

    .zuo,
    .you {
      background-size: 100% 100%;
      width: 29px;
      height: 20px;
      margin-top: 8px;
    }

    .zuo {
      background: url("@/assets/img/xiezuo.png") no-repeat;
    }

    .you {
      background: url("@/assets/img/xieyou.png") no-repeat;
    }
  }

  .mapwrap {
    height: 480px;
    width: 100%;
    // padding: 0 0 10px 0;
    box-sizing: border-box;
    position: relative;

    .quanguo {
      position: absolute;
      right: 20px;
      top: -46px;
      width: 80px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: #00f7f6;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5),
        0 0 6px rgba(0, 237, 237, 0.4);
      z-index: 10;
    }
  }
}
</style>
